package com.contract.management.web;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.contract.management.domain.CommJpaRepository;
import com.contract.management.domain.User;
import com.contract.management.service.UserService;
import com.contract.management.util.StrUtils;

@Controller
public class IndexController {
	
	@Value("${office.basepath}")
	private String basePath;
	@Autowired
	private CommJpaRepository repo;
	
	@Autowired
	private UserService service;
	
	@RequestMapping("/")
	public String home() {
		return "redirect:/index";
	}
	
	@RequestMapping("/index")
	public String index(HttpSession session, Model model) {
		User user = (User)session.getAttribute("user");
		long htzs, ygz, wgz, zfgz, ywc; 
		if(user.getRight() == 5) {
			htzs = repo.queryOne("select count(*) from Contract where user.id = ?0", user.getId());
			ygz = repo.queryOne("select count(*) from Contract where status <> -1 and curNode.id > 7 and user.id = ?0", user.getId());
			wgz = repo.queryOne("select count(*) from Contract where status <> -1 and curNode.id <= 7 and user.id = ?0", user.getId());
			zfgz = repo.queryOne("select count(*) from Contract where status = -1 and curNode.id > 7 and user.id = ?0", user.getId());
			ywc = repo.queryOne("select count(*) from Contract where status = 1 and user.id = ?0", user.getId());
		} else {
			htzs = repo.queryOne("select count(*) from Contract");
			ygz = repo.queryOne("select count(*) from Contract where status <> -1 and curNode.id > 7");
			wgz = repo.queryOne("select count(*) from Contract where status <> -1 and curNode.id <= 7");
			zfgz = repo.queryOne("select count(*) from Contract where status = -1 and curNode.id > 7");
			ywc = repo.queryOne("select count(*) from Contract where status = 1");
		}
		//录入合同总数
		model.addAttribute("htzs", htzs);
		//已盖章合同总数
		model.addAttribute("ygz", ygz);
		//未盖章合同总数
		model.addAttribute("wgz", wgz);
		//作废盖章合同总数
		model.addAttribute("zfgz", zfgz);
		//已完成合同总数
		model.addAttribute("ywc", ywc);
		
		model.addAttribute("ywlxs", repo.query("select new map(s.id as id, concat((CASE s.bigClass.area WHEN 'A' THEN '上海' WHEN 'B' THEN '苏州' WHEN 'C' THEN '成都' END), '-',  s.bigClass.name, '-', s.name) as name) from ContSmallClass s order by s.id"));
		
		return "index";
	}
	
	@RequestMapping("/noright")
	public String noright(Model model) {
		model.addAttribute("text", "该操作无效");
		return "show_error_message";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletResponse resp) {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Methods", "GET");
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginSubmit(Model model, HttpSession session, String username, String password, String redirect) {
		if(StrUtils.isEmpty(redirect) || "/logout".equals(redirect) || "/login".equals(redirect)) {
			redirect = "/index";
		}
		User user = service.checkLogin(username, password);
		if(user == null) {
			model.addAttribute("error", "用户名或密码 错误");
			return "login";
		} else if(!user.isAllowLogin()) {
			model.addAttribute("error", "您被禁止登陆系统");
			return "login";
		}
		session.setAttribute("user", user);
		
		if("admin".equals(user.getUsername())) {
			user.setRight(6);
		} else {
			if(user.getDept() == null || user.getDept().getRight() == null) {
				model.addAttribute("error", "您没有使用权限");
				return "login";
			} else {
				user.setRight(user.getDept().getRight().getId());
			}
		}
		return "redirect:" + redirect;
	}
	
	@RequestMapping(value = "/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/login";
	}
	
	@RequestMapping(value = "/todo")
	public String todo(Model model) {
		model.addAttribute("title", "提示信息");
		model.addAttribute("text", "页面制作中，请等待......");
		model.addAttribute("type", "info");
		return "show_message";
	}
	
	@RequestMapping("/templates/{fileName:.+}")
	public void getTemplateDoc(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
		// 告诉浏览器用什么软件可以打开此文件
	    response.setHeader("content-Type", "application/msword");
	    // 下载文件的默认名称
	    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
	    
	    File f = new File(basePath + "/templates", fileName);
	    byte[] buf = new byte[1024];
	    int len;
	    try(FileInputStream fis = new FileInputStream(f);
	    		OutputStream os = response.getOutputStream()) {
	    	while((len = fis.read(buf)) != -1) {
	    		os.write(buf, 0, len);
	    	}
	    } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/contracts/{fileName:.+}")
	public void getContractseDoc(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
		// 告诉浏览器用什么软件可以打开此文件
	    response.setHeader("content-Type", "application/msword");
	    // 下载文件的默认名称
	    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
	    
	    File f = new File(basePath + "/contracts", fileName);
	    byte[] buf = new byte[1024];
	    int len;
	    try(FileInputStream fis = new FileInputStream(f);
	    		OutputStream os = response.getOutputStream()) {
	    	while((len = fis.read(buf)) != -1) {
	    		os.write(buf, 0, len);
	    	}
	    } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/pic/{fileName:.+}")
	public void showPic(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
		resp.setContentType("image/" + suffixName);
		File f = new File(basePath + "uploads", fileName);
		if(!f.exists()) return;
		try (FileInputStream fis = new FileInputStream(f);
				OutputStream os = resp.getOutputStream()){
			BufferedImage img = ImageIO.read(fis);
			ImageIO.write(img, suffixName, os);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	@RequestMapping("/pdf/{fileName:.+}")
	public void showPdf(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
		resp.setContentType("application/pdf");
		File f = new File(basePath + "uploads", fileName);
		if(!f.exists()) return;
		byte[] buff = new byte[1024];
		int len = 0;
		try (FileInputStream fis = new FileInputStream(f);
				OutputStream os = resp.getOutputStream()){
			while((len = fis.read(buff)) > 0) {
				os.write(buff, 0, len);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	@RequestMapping("/temp/pic/{fileName:.+}")
	public void showTempPic(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
		resp.setContentType("image/" + suffixName);
		File f = new File(basePath + "temp", fileName);
		if(!f.exists()) return;
		try (FileInputStream fis = new FileInputStream(f);
				OutputStream os = resp.getOutputStream()){
			BufferedImage img = ImageIO.read(fis);
			ImageIO.write(img, suffixName, os);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	@RequestMapping("/download/{fileName:.+}")
	@ResponseBody
	public void download(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		resp.setHeader("content-type", "application/octet-stream");
		resp.setContentType("application/octet-stream");
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		int i;
		String filePath = basePath + "uploads/" + fileName;
		try(BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
				OutputStream os = resp.getOutputStream()) {
			while((i = is.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/download/pdf/{fileName}")
	@ResponseBody
	public void downloadPdf(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		resp.setHeader("content-type", "application/octet-stream");
		resp.setContentType("application/octet-stream");
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
		byte[] buff = new byte[1024];
		int i;
		String filePath = basePath + "contracts/" + fileName + ".pdf";
		try(BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
				OutputStream os = resp.getOutputStream()) {
			while((i = is.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/temp/download/{fileName:.+}")
	@ResponseBody
	public void tempDownload(HttpServletRequest req, HttpServletResponse resp, @PathVariable String fileName) {
		resp.setHeader("content-type", "application/octet-stream");
		resp.setContentType("application/octet-stream");
		resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
		int i;
		String filePath = basePath + "temp/" + fileName;
		try(BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
				OutputStream os = resp.getOutputStream()) {
			while((i = is.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 上传图片，先保存在临时目录下
	 * 
	 * @param request
	 * @param session
	 * @param files
	 * @return
	 */
	@RequestMapping(value = "/file/add", method = RequestMethod.POST)
	@ResponseBody
	public Object addFile(HttpServletRequest request, 
				HttpSession session, 
				@RequestParam("upload_file") MultipartFile[] files, 
				@RequestParam("upload_pic") MultipartFile[] picFiles, 
				@RequestParam("upload_doc") MultipartFile[] docFiles) {
		if(picFiles.length > 0) {
			files = picFiles;
		} else if(docFiles.length > 0) {
			files = docFiles;
		}
		String context = request.getContextPath();

		String filePath = basePath + "temp";
		List<String> preview = new ArrayList<String>();
		List<Map<String, Object>> previewConfig = new ArrayList<Map<String, Object>>();
		for (MultipartFile file : files) {
			if (!file.isEmpty()) {
				String oraName = file.getOriginalFilename();
				String filename = StrUtils.getUuidName(file.getOriginalFilename());
				try {
					file.transferTo(new File(filePath, filename));
					String url = context + "/temp/pic/" + filename;
					//图片路径URL
					preview.add(url);	
					Map<String, Object> map = new HashMap<String, Object>() {{
						put("caption", oraName);
						put("width", "120px");
						put("url", context + "/file/del/" + filename);
						put("downloadUrl", url);
						put("size", file.getSize());
						put("key", 0);
						put("extra", new HashMap<String, String>(){{
							put("filename", filename);
							put("oraName", oraName);
						}});
					}};
					previewConfig.add(map);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("initialPreview", preview);
		map.put("initialPreviewConfig", previewConfig);
		return map;
	}
	

	/**
	 * 删除临时目录下文件
	 * @param resp
	 * @param filename
	 */
	@RequestMapping(value = "/file/del/{filename:.+}", method = RequestMethod.POST)
	@ResponseBody
    public void delFile(HttpServletResponse resp, @PathVariable String filename) {
		String filePath = basePath + "temp";
		
		if(filename != null) {
			File f = new File(filePath, filename);
			f.delete();
		}
		try {
			resp.getWriter().write("{}");
			resp.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
